package youdu

import (
	"encoding/json"
	"fmt"
	"strings"
	"youdu/model"
)

const (
	API_PATH_DEPT_CREATE string = "/cgi/dept/create"
	API_PATH_DEPT_UPDATE string = "/cgi/dept/update"
	API_PATH_DEPT_DELETE string = "/cgi/dept/delete"
	API_PATH_DEPT_LIST   string = "/cgi/dept/list"
	API_PATH_DEPT_GETID  string = "/cgi/dept/getid"
	API_PATH_DEPT_SORT   string = "/cgi/dept/sort"
)

// 创建部门
func (c *Org) DepartmentCreate(data model.DepartmentInfo) (int, error) {
	api := API_PATH_DEPT_CREATE

	resp, err := Tools.ApiRequest(c.Server, c.Buin, c.AppId, c.EncodedAesKey, api, data)
	if err != nil {
		return 0, err
	}

	var result struct {
		Id int `json:"id"`
	}
	if err := json.Unmarshal(resp, &result); err != nil {
		return 0, err
	}

	return result.Id, nil
}

// 修改部门
func (c *Org) DepartmentUpdate(data model.DepartmentInfo) error {
	api := API_PATH_DEPT_UPDATE
	// 检查部门ID是否大于0
	if data.Id <= 0 {
		return fmt.Errorf("部门ID必须大于0")
	}
	// 检查部门名称是否为空
	if data.Name == "" {
		return fmt.Errorf("部门名称不能为空")
	}
	_, err := Tools.ApiRequest(c.Server, c.Buin, c.AppId, c.EncodedAesKey, api, data)
	return err
}

// 删除部门
func (c *Org) DepartmentDelete(id int) error {
	api := fmt.Sprintf("%s?id=%d", API_PATH_DEPT_DELETE, id)
	// 检查部门ID是否大于0
	if id <= 0 {
		return fmt.Errorf("部门ID必须大于0")
	}
	_, err := Tools.ApiRequest(c.Server, c.Buin, c.AppId, c.EncodedAesKey, api, nil)
	return err
}

// 获取部门列表
func (c *Org) DepartmentListGet(id int) (*model.DepartmentList, error) {
	api := fmt.Sprintf("%s?id=%d", API_PATH_DEPT_LIST, id)
	var deptList model.DepartmentList

	resp, err := Tools.ApiRequest(c.Server, c.Buin, c.AppId, c.EncodedAesKey, api, nil)
	if err != nil {
		return nil, err
	}

	if err := json.Unmarshal(resp, &deptList); err != nil {
		return nil, err
	}

	return &deptList, nil
}

// 获取携带别名的部门ID列表
// 参数： alias 部门alias。携带时查询该alias对应的部门id。不带alias参数时查询全部映射关系。
func (c *Org) DepartmentAliasListGet(alias string) (*model.DepartmentAliasList, error) {
	api := API_PATH_DEPT_GETID
	if alias == "" {
		api = fmt.Sprintf("%s?alias=%s", api, alias)
	}

	resp, err := Tools.ApiRequest(c.Server, c.Buin, c.AppId, c.EncodedAesKey, api, nil)
	if err != nil {
		return nil, err
	}

	var deptInfo model.DepartmentAliasList
	if err := json.Unmarshal(resp, &deptInfo); err != nil {
		return nil, err
	}

	return &deptInfo, nil
}

// 修改部门排序
func (c *Org) DepartmentSortUpdate(data model.DepartmentSort) error {
	api := API_PATH_DEPT_SORT

	_, err := Tools.ApiRequest(c.Server, c.Buin, c.AppId, c.EncodedAesKey, api, data)
	return err
}

/************************************************************/

func (c *Org) DepartmentSave(dept model.DepartmentInfo) error {
	// // 查询部门是否已经存在
	_, err := c.DepartmentCreate(dept)
	// 如果包含 the dept-id already exists 字符就调用更新接口
	if err != nil {
		if strings.Contains(err.Error(), "the dept-id already exists") {
			err = c.DepartmentUpdate(dept)
			// fmt.Println("更新部门资料成功")
		}
	}
	return err
}
